//
//  LGTHomeSearchVC.swift
//  KJLGT
//
//  Created by jenkin on 2019/9/4.
//  Copyright © 2019年 jenkin. All rights reserved.
//

import UIKit
import ZHRefresh

class LGTHomeSearchVC: LGTBaseVC, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate{
    var tableView:UITableView?
    var data:Array<TaskModel> = []
    var page:Int = 1
    var searchBar:SMSearchBar = SMSearchBar()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.searchBar.becomeFirstResponder()
        // Do any additional setup after loading the view.
    }
    
    override func setUI() {
        super.setUI()
        self.setBavBarStyle(navBarHiden: false, title: "", back: true)

        self.searchBar.placeholder = "简单下载"
        self.searchBar.delegate = self
        self.searchBar.setBackgroundColor(ViewBackColor, textFieldBackgroundColor: ViewBackColor, fontColor: GrayColor)
        self.navBar.addSubview(self.searchBar)
        self.searchBar.snp.makeConstraints { (make) in
            make.height.equalTo(26)
            make.left.equalTo(49)
            make.bottom.equalTo(-SizeFit(9))
            make.right.equalTo(-56)
        }
        
        let searchBtn = LGTViewCreateUtil.share.createTextLGTButton(title: "搜索", font: KFont(size: 16), color: TextColor, selectedColor: TextColor, dW: SizeFitFloat(5), dH: SizeFitFloat(5))
        self.navBar.addSubview(searchBtn)
        searchBtn.addTarget(self, action: #selector(searchAction), for: UIControl.Event.touchUpInside)
        searchBtn.snp.makeConstraints { (make) in
            make.height.equalTo(16)
            make.width.equalTo(33)
            make.centerY.equalTo(self.searchBar)
            make.right.equalTo(-12)
        }
        
        self.tableView = UITableView.init(frame: CGRect.init(x: 0.0, y: NavBarH(), width: Double(KScreenW), height: Double(KScreenH) - NavBarH()), style: UITableView.Style.plain)
        self.view.addSubview(self.tableView!)
        self.tableView?.backgroundColor = ViewBackColor
        self.tableView?.separatorStyle = UITableViewCell.SeparatorStyle.none
        self.tableView?.delegate = self
        self.tableView?.dataSource = self
        self.tableView?.register(LGTHomeCell.classForCoder(), forCellReuseIdentifier: "cell")
//        weak var weakSelf = self
//        self.tableView?.header = ZHRefreshHeader.headerWithRefreshing(block: {
//            weakSelf?.page = 1
//            weakSelf?.tableView?.footer?.endRefreshing()
//            weakSelf?.getData()
//        })
//
//        self.tableView?.footer = ZHRefreshBackNormalFooter.footerWithRefreshing(block: {
//            weakSelf?.page += 1
//            weakSelf?.tableView?.header?.endRefreshing()
//            weakSelf?.getData()
//        })
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:LGTHomeCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! LGTHomeCell
        cell.model = self.data[indexPath.row]
        return cell
    }
    
    func getData(){
        weak var weakSelf = self
        let search:String = self.searchBar.text ?? ""
        LGTHttpUtil.httpUtil.requestData(url: LLZ_Task_List_URL, param: ["page": self.page, "search": search], showMessage: false, success: { (json) in
            weakSelf?.tableView?.header?.endRefreshing()
            weakSelf?.tableView?.footer?.endRefreshing()
            let data:Array<Dictionary<String, Any>> =  json["data"] as? Array<Dictionary<String, Any>> ?? Array.init()
            var modeArray:Array<TaskModel> = Array.init()
            for i in 0..<data.count{
                let param:Dictionary<String, Any> = data[i]
                let model:TaskModel = try! lgtDecode(TaskModel.self, param: param)
                modeArray.append(model)
            }
            
            if weakSelf?.page == 1{
                weakSelf?.data = modeArray
                
            }else{
                if weakSelf?.data == nil{
                    weakSelf?.data = Array.init()
                }
                weakSelf?.data.append(contentsOf: modeArray)
            }
            
            if modeArray.count == 0{
                weakSelf?.tableView?.footer?.endRefreshingWithNoMoreData()
            }else{
                weakSelf?.tableView?.footer?.resetNoMoreData()
            }
            weakSelf?.tableView?.reloadData()
        }, failure: { (json) in
            weakSelf?.tableView?.header?.endRefreshing()
            weakSelf?.tableView?.footer?.endRefreshing()
        })
    }
    
    @objc func searchAction(){
//        self.view.endEditing(true)
//        self.tableView?.header?.beginRefreshing()
        
        self.page = 1
        self.getData()
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        self.searchAction()
    }
}
